const Koa = require('koa')
const Router = require('koa-router')
const staticFiles = require('koa-static')
const koaFavicon = require('koa-favicon')
const koaBody = require('koa-body')
const fs = require('fs')
const path = require('path')

const renderString = require('./util/renderString')
// const apis = require(path.join(__dirname, './apis'))
const apis = require('./apis')
const session = require('./util/session')

const isDev = process.env.NODE_ENV == 'development'
console.log('isDev', isDev)
const app = new Koa()
session.init(app)

app.use(koaBody())
app.use(koaFavicon(path.join(__dirname, '../favicon.ico')))

// API 接口请求处理
const router = new Router({
    prefix: apis.prefix
})
router.post('login', require('./util/handle-login'))
router.post(apis.getApis(), require('./util/proxy'))

// HTML 页面请求处理
if (!isDev) {
    app.use(staticFiles(path.join(__dirname, '../dist/'), {}));
    const serverbundle = require('../dist/server-entry')
    const template = fs.readFileSync(path.join(__dirname, "../dist/index.pug"), 'utf-8')
    app.use(async (ctx, next) => {
        const result = renderString(serverbundle, template, ctx, next)
        await next();
    });
} else {
    const devStatic = require('./util/dev-static')
    devStatic(app, router)
}

app.use(router.routes());
// 404等错误处理
app.use(async (ctx, next) => {
    const status = ctx.response.status
    const method = ctx.request.method
    switch (status) {
        case 404:
            if (method === 'POST') {
                ctx.response.status = 404
                ctx.response.body = {
                    status: ctx.response.status,
                    message: ctx.response.message,
                }
            } else {
                // 渲染404页面，由react-router进行控制了
            }
            break;
        default:
            break;
    }
    await next()
})
app.on('error', err => {
    console.error('server error', err)
});

app.listen(3031)
